<template>
	<view>
		<view class="readgbox" v-for="(item, index) in list" :key="index" v-if="index == current">
			<view class="readgboxeng">{{ item.word }}</view>
			<view class="readgboxtext">{{ item.chinese }}</view>
			<view class="mt20">
				<u-icon name="volume" color="#999999" size="30" @tap="getVoice(item.word)"></u-icon>
			</view>
			<!-- 中间显示 -->
			<view class="readgbox_cen mt20">
				<view class="readgbox_cenbox" v-if="voiceRecording > 0">
					<!-- 录音过程中 -->
					<view class="readgbox_cenbox_pro" v-if="voiceRecording == 1">
						<image src="../../../static/index/process.png" mode=""></image>
					</view>
					<view class="" v-else>
						<!-- 录制1颗星 -->
						<view class="readgbox_cenbox_per" v-if="score < 80">
							<view class="d-c-c mb20">
								<view class="">
									<image src="../../../static/index/star_icon.png" mode=""></image>
								</view>
							</view>
							<view class="readgbox_cenbox_text">Try again!</view>
						</view>
						<!-- 录制2颗星 -->
						<view class="readgbox_cenbox_per" v-if="score >= 80 && score < 90">
							<view class="d-c-c mb20">
								<view class="mr30">
									<image src="../../../static/index/star_icon.png" mode=""></image>
								</view>
								<view class="">
									<image src="../../../static/index/star_icon.png" mode=""></image>
								</view>
							</view>
							<view class="readgbox_cenbox_text">Good！</view>
						</view>
						<!-- 录制3颗星 -->
						<view class="readgbox_cenbox_per" v-if="score >= 90">
							<view class="d-c-c mb20">
								<view class="mr30" style="margin-bottom: -30rpx;">
									<image src="../../../static/index/star_icon.png" mode=""></image>
								</view>
								<view class="mr30"  style="margin-top: -20rpx;">
									<image src="../../../static/index/star_icon.png" mode=""></image>
								</view>
								<view class=""  style="margin-bottom: -30rpx;">
									<image src="../../../static/index/star_icon.png" mode=""></image>
								</view>
							</view>
							<view class="readgbox_cenbox_text">Perfect!</view>
						</view>
						<view class="readgbox_cenbox_num">{{ score }}</view>
					</view>
				</view>
			</view>
			<!-- 读音按键 -->
			<view class="d-a-c">
				<view class="readgbox_boreadgbo">
					<view class="" @tap="getVoice(item.word)">
						<image src="../../../static/index/readgbo.png" mode=""></image>
					</view>
					<view class="">播放</view>
				</view>
				<view class="readgbox_boreadgdu">
					<view class="" @touchstart="startRecording" @touchend="stopRecording(item.word)">
						<image src="../../../static/index/readgdu.png" mode=""></image>
					</view>
					<view class="">按住录音</view>
				</view>
				<view class="readgbox_boreadgbo">
					<view class="" @tap="myVoice">
						<image src="../../../static/index/readgwo.png" mode=""></image>
					</view>
					<view class="">我的读音</view>
				</view>
			</view>
			<!-- 翻页 -->
			<view class="d-c-c" style="margin-bottom: 1vh;">
				<!-- <view class="d-c-c mr20 berboxz" @click="prev">
					<u-icon name="arrow-left" color="#999999" size="28"></u-icon>
				</view> -->
				<view class="f30 fb gray3">
					{{ current+1 }} / {{ total }}
				</view>
				<!-- <view class="d-c-c ml20 berboxz" @click="next">
					<u-icon name="arrow-right" color="#999999" size="28"></u-icon>
				</view> -->
			</view>
			<view class="readgbox_bot" @tap="next">下一词</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				uploadUrl: getApp().globalData.uploadUrl,
				imgUrl: getApp().globalData.imgUrl,
				ids: '',
				list: [],
				current: 0, //现数
				total: 1, //总数
				voiceRecording: 0, //0未开始，1录制中，2录制结束
				score: 0, //分数
				myVoiceSrc: '',
				recorderManager: null,
				isRecording: false,
			}
		},
		onLoad(option) {
			if (!this.$store.state.isLogin) {
				uni.$u.toast('登录超时请重新登录')
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login',
					});
				}, 1500)
				return false
			} else {
				if (option.ids) {
					this.ids = option.ids
					this.getList()
					// #ifdef APP
					this.init()
					// #endif
				} else {
					uni.navigateBack()
				}
			}
		},
		methods: {
			init() {
				const appAuthorize = uni.getAppAuthorizeSetting()
				if (appAuthorize.microphoneAuthorized !== 'authorized') {
					uni.showModal({
						title: '',
						content: '未开启录音权限，是否现在去开启',
						showCancel: true,
						confirmColor: '#387BEF',
						success: function(res) {
							if (res.confirm) {
								uni.openAppAuthorizeSetting({
									success (res) {
										console.log(res)
									}
								})
							}
						}
					})
				}
			},
			getList() {
				this.$u.post(this.$u.api.wordsByIds, {
					ids: this.ids
				}).then((res) => {
					this.list = res.data
					this.total = res.data.length
					
					setTimeout(() => {
						this.getVoice(this.list[0].word)
					}, 50)
				}).catch((err) => {
					console.log(err)
				})
			},
			// 获取单词音频
			getVoice(word) {
				this.$u.post(this.$u.api.wordVoice, {
					word: word,
					type: this.$store.state.voiceType
				}).then((res) => {
					// 播放音频
					this.utils.playAudio(this.imgUrl + res.data)
				}).catch((err) => {
					console.log(err)
					uni.$u.toast(err.data.msg)
				})
			},
			// 开始录音
			startRecording() {
				// #ifdef APP
				const appAuthorize = uni.getAppAuthorizeSetting()
				if (appAuthorize.microphoneAuthorized !== 'authorized') {
					uni.$u.toast('请前往设置，开启录音权限')
					return false
				}
				// #endif
				if (!this.isRecording) {
					uni.showLoading({
						title: '录音中...'
					})
					
					this.recorderManager = uni.getRecorderManager()
					this.recorderManager.start({ 
						sampleRate: 16000, // 设置采样率为16000Hz
						bitrate: 16, // 设置比特率为16
						channels: 1, // 设置声道为1（单声道）
						duration: 60000, // 录音的最大时长，单位 ms
						numberOfChannels: 1, // 声道数，默认为1，立体声设置为2
						encodeBitRate: 48000, // 编码码率
						audioSource: 'auto', // 音频源
						format: 'mp3' // 音频格式，默认为'aac'
					})
					this.voiceRecording = 1
					this.score = 0
					this.isRecording = true
				}
			},
			// 结束录音
			stopRecording(word) {
				if (this.isRecording) {
					uni.hideLoading()
					
					this.recorderManager.stop() // 停止录音
					this.recorderManager.onStop((res) => {
						console.log('录音成功', res)
						this.myVoiceSrc = res.tempFilePath
						this.recordCheck(word, res.tempFilePath)
					})
					this.isRecording = false
				}
			},
			// 我的读音
			myVoice() {
				if (this.myVoiceSrc) {
					this.utils.playAudio(this.myVoiceSrc)
				}
			},
			// 上一个
			prev() {
				if (this.current > 1) {
					this.current--
					
					this.getVoice(this.list[this.current].word)
				}
			},
			// 下一个
			next() {
				if (this.current + 1 < this.total) {
					this.current++
					this.voiceRecording = 0
					this.score = 0
					
					this.getVoice(this.list[this.current].word)
				} else {
					uni.$u.toast('跟读打分结束')
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/indexhome/review'
						})
					}, 1500)
				}
			},
			// 上传录音并比较
			async recordCheck(word, filePath) {
				const file = await this.uploadAudio(filePath)
				if (file) {
					this.$u.post(this.$u.api.tencentWordVoiceCheck, {
						word: word,
						voice: file
					}).then((res) => {
						console.log(res.data)
						let data = res.data
						this.voiceRecording = 2
						this.score = Math.round(data)
					}).catch((err) => {
						console.log(err)
						this.voiceRecording = 0
						uni.$u.toast('打分失败')
						return false
					})
				} else {
					uni.$u.toast('打分失败')
					return false
				}
			},
			uploadAudio(filePath) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.uploadUrl,
						filePath: filePath,
						name: 'file',
						formData: {
							token: this.$store.state.token
						},
						header: {
							'content-type': 'multipart/form-data'
						},
						success: (uploadFileRes) => {
							// console.log('录音上传成功', uploadFileRes)
							if (uploadFileRes.statusCode == 200) {
								let res = JSON.parse(uploadFileRes.data)
								if (res.code == 1) {
									resolve(res.data.fullurl)
								}
							}
							reject()
						},
						fail: (uploadFileErr) => {
							// console.log('录音上传失败', uploadFileErr)
							reject(uploadFileErr)
						}
					})
				})
			},
		}
	}
</script>

<style lang="less" scoped>
	.readgbox {
		width: 100%;
		// margin: 80rpx auto 0;
		text-align: center;
		padding: 2vh 30rpx;

	}

	.readgboxeng {
		font-weight: bold;
		font-size: 70rpx;
		color: #333333;
		margin-bottom: 1vh;
	}

	.readgboxtext {
		font-weight: bold;
		font-size: 30rpx;
		color: #333333;
	}

	.berboxz {
		border: 1rpx solid #999999;
		border-radius: 100%;
		width: 50rpx;
		height: 50rpx;
	}

	.readgbox_cen {
		height: 370rpx;
		margin: 1vh 0 4vh;
	}

	.readgbox_cenbox {
		background-color: #FFFFFF;
		border-radius: 30rpx;
		height: 370rpx;
		margin: 0 30rpx;
	}

	.readgbox_boreadgbo {
		margin-bottom: 20rpx;

		image {
			width: 100rpx;
			height: 100rpx;
		}
	}

	.readgbox_boreadgdu {
		margin-bottom: 20rpx;

		image {
			width: 142rpx;
			height: 142rpx;
		}
	}

	.readgbox_bot {
		height: 100rpx;
		background: #FFFFFF;
		border-radius: 50rpx;
		text-align: center;
		line-height: 100rpx;
		font-size: 30rpx;
		font-weight: bold;
		margin: 1vh auto;
	}
	.readgbox_cenbox_pro{
		height: 370rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		image{
			width: 315rpx;
			height: 170rpx;
		}
	}
	.readgbox_cenbox_per{
		padding-top: 50rpx;
		image{
			width: 118rpx;
			height: 117rpx;
		}
	}
	.readgbox_cenbox_text{
		font-weight: 800;
		font-size: 48rpx;
		color: #FDE34E;
		margin-bottom: 20rpx;
	}
	.readgbox_cenbox_num{
		font-weight: bold;
		font-size: 62rpx;
		color: #387BEF;
	}
</style>
